<?php
namespace app\admin\controller;
use Qiniu\Auth as Auth;
use Qiniu\Storage\UploadManager;
//商品管理
class Goods extends Common
{
	//商品列表
    public function goods_list()
    {
		$where=array('a.g_id'=>array('gt',0));
        $where['f.gn_status']=array('in','1,2');
        $where['a.g_status']=array('in','1,2');
        $name=Request()->param('name');
		//名称
		$status=Request()->param('status');
		//状态
        $start_time=strtotime(Request()->param('start_time'));
        $end_time=strtotime(Request()->param('end_time'));
        $page=Request()->param('page');
        $size=Request()->param('size');
        if($page<1){
            $page=1;
        }
        if($size<15){
            $size=15;
        }
        $now=($page-1)*$size;
		if($name!=''){
			$where['a.g_name']=array('like','%'.$name.'%');
		}
		if($status>0){
			if($status==1){
				$where['f.gn_status']=1;
			}else{
				$where['f.gn_status']=2;
			}
			
		}
        $where_time=array(array('gt',0),array('gt',0));
        if($start_time>0){
            $where_time[]=array('egt',$start_time);
        }else{
            $start_time='';
        }
        if($end_time>0){
            $where_time[]=array('elt',$end_time);
        }else{
            $end_time='';
        }
        $where['f.gn_create_time']=$where_time;
        $goods=db('goods a')
            ->field("a.g_id,a.g_name,a.g_status,a.g_is_index_recommen,a.gl_ids,a.g_sales,b.gt_name,c.gb_name,d.gt_name as gt_name1,e.gt_name as gt_name2,f.*")
            ->join('fr_goods_type b','a.gt_id = b.gt_id','left')
            ->join('fr_goods_type d','d.gt_id = b.gt_pid','left')
            ->join('fr_goods_type e','e.gt_id = d.gt_pid','left')
            ->join('fr_goods_brand c','a.gb_id = c.gb_id','left')
            ->join('fr_goods_norm f','a.g_id=f.g_id','left')
			->order('a.g_sort desc,a.g_status,f.gn_sort desc,f.gn_status,f.gn_id desc')
			->where($where)
            ->limit("$now,$size")
			->select();
        //标签列表
        foreach($goods as $k=>$v){
            $goods[$k]['gn_details_price']=round($v['gn_price']/$v['gn_details_number'],2).'/'.$v['gn_details_unit'];
            if (preg_match('/,1,/', $v['gl_ids'])) {
                //匹配成功
                $goods[$k]['special']=1;
            } else {
                //匹配失败
                $goods[$k]['special']=0;
            }
        }
        $count=db('goods a')
            ->join('fr_goods_norm f','a.g_id=f.g_id','left')
            ->where($where)
            ->count();
        //等级信息
        $page_str=page($page,$size,$count,count($goods));//分页
        $this->view->assign('page_str',$page_str);
		$this->view->assign('data',$goods);
		$this->assign('status',$status);
		$this->assign('name',$name);
        $this->assign('start_time',$start_time);
        $this->assign('end_time',$end_time);
        $this->assign('page',$page);
        $this->assign('size',$size);
        $this->assign('count',$count);
        return $this->view->fetch();

    }
	//添加商品
	public function add_goods(){
		if(request()->isGet()){
			//get，加载页面
            $type=db('goods_type')
                ->where(array('gt_status'=>1))
                ->order("gt_sort desc,gt_type")
                ->select();
            //分类
            $type1=array();
            $type2=array();
            foreach($type as $k=>$v){
                if($v['gt_type']==1){
                    $type1[]=$v;
                }
                if($v['gt_type']==2){
                    $type2[]=$v;
                }
                if($v['gt_type']==3){
                    $type3[]=$v;
                }
            }
            $label=db('goods_label a')
                ->where(array('a.gl_status'=>1,'gl_id'=>array('neq',2)))
                ->order("a.gl_sort")
                ->select();
            //标签
            $brand=db('goods_brand a')
                ->where(array('a.gb_status'=>1))
                ->order("a.gb_sort")
                ->select();
            //品牌
            $this->assign('type1',$type1);
            $this->assign('type2',$type2);
            $this->assign('type3',$type3);
            $this->assign('label',$label);
            $this->assign('brand',$brand);
			return $this->view->fetch();
		}else if(request()->isAjax()){
		    $data1=request()->post();
			$data['g_name']=$data1['g_name'];
            $data['gt_id']=$data1['gt_id'];
            $data['gb_id']=$data1['gb_id'];
            $data['g_sort']=$data1['g_sort'];
            $data['g_status']=$data1['g_status'];
            $data['g_is_index_recommen']=$data1['g_is_index_recommen'];
            if(!isset($data1['label'])){
                $data1['label']='';
            }
            $data['label']=$data1['label'];
            if(!isset($data1['editorValue'])){
                $data1['editorValue']='';
            }
            $data['editorValue']=$data1['editorValue'];
			if($data['g_name']==''){
                return return_json(array('code'=>0,'msg'=>'请输入商品名称'),'添加商品');
            }
            $system=db('system')->find();
            $gt_id=$data['gt_id'];
            $data['g_content']=$data['editorValue'];
            unset($data['editorValue']);
            $goods_type=db('goods_type a')
                ->field("a.*,b.gt_id as gt_id2,c.gt_id as gt_id1")
                ->join("fr_goods_type b","a.gt_pid = b.gt_id","left")
                ->join("fr_goods_type c","b.gt_pid = c.gt_id","left")
                ->where(array('a.gt_status'=>1,'a.gt_id'=>$gt_id))
                ->find();
            if(empty($goods_type)){
                return return_json(array('code'=>0,'msg'=>'请选择可使用的分类'),'添加商品');
            }
            $data['gt_id1']=$goods_type['gt_id1'];
            $data['gt_id2']=$goods_type['gt_id2'];
            $label = $data['label'];
            if(!empty($label)){
                $label_str = ','.implode(',',$label).',';
            }else{
                $label_str = '';
            }
            $data['gl_ids']=$label_str;
            $data['g_create_time']=time();
            $data['g_add_user_id']=session('uid');
            $data['g_add_user_name']=session('user.real_name');
            unset($data['label']);
            //以上为商品属性判断
            $gn_name=$data1['gn_name'];
            $gn_price=$data1['gn_price'];
            $gn_stock=$data1['gn_stock'];
            $gn_old_price=$data1['gn_old_price'];
            $gn_weight=$data1['gn_weight'];
            $gn_details_number=$data1['gn_details_number'];
            $gn_details_unit=$data1['gn_details_unit'];
            $gn_sort=$data1['gn_sort'];
            $norm=array();
            foreach($gn_name as $k=>$v){
                if($v!='' && $gn_price[$k] > 0 && $gn_weight[$k] > 0){
                    if($gn_old_price[$k] > 0 && $gn_old_price[$k] < $gn_price[$k]){
                        return return_json(array('code'=>0,'msg'=>'所有的原价都必须大于出售价格或为0'),'添加商品');
                    }
                    if($gn_old_price[$k]<=0){
                        $gn_old_price[$k]=0;
                    }
                    if($gn_stock[$k]<=0){
                        $gn_stock[$k]=0;
                    }
                    if($gn_details_number[$k]<=1){
                        $gn_details_number[$k]=1;
                    }
                    if($gn_details_unit[$k]<=1){
                        $gn_details_unit[$k]='件';
                    }
                    if($gn_sort[$k]<=0){
                        $gn_sort[$k]=0;
                    }
                    $norm[$k]=array('gn_price'=>$gn_price[$k],'gn_old_price'=>$gn_old_price[$k],'gn_stock'=>$gn_stock[$k],'gn_name'=>$v,'gn_weight'=>$gn_weight[$k],'gn_one_number'=>'','gn_status'=>1,'gn_create_time'=>time(),'gn_sort'=>$gn_sort[$k],'gn_add_user_id'=>session('uid'),'gn_add_user_name'=>session('user.real_name'),'gn_details_number'=>$gn_details_number[$k],'gn_details_unit'=>$gn_details_unit[$k]);
                }
            }
            if(empty($norm) || count($norm)<1){
                return return_json(array('code'=>0,'msg'=>'至少有一个商品规格'),'添加商品');
            }
            $upload = new Upload();
            $file =Request()->file("g_img");
            if(!$file){
                $data['g_img']=$system['goods_img'];
            }else{
                $return=$upload->upload($file);
                if($return['code']!=1){
                    return return_json(array('code'=>0,'msg'=>'图片上传失败:'.$return['msg']),'上传图片');
                }else{
                    $data['g_img']=$return['url'];
                }
            }
            $file =Request()->file("gi_img");
            if(!$file){
                $image=array(array('gi_img'=>$system['goods_image'],'gi_sort'=>0,'gi_status'=>1,'gi_create_time'=>time(),'gi_add_user_id'=>session('uid'),'gi_add_user_name'=>session('user.real_name')));
            }else{
                foreach($file as $v){
                    $return=$upload->upload($v);
                    if($return['code']!=1){
                        return return_json(array('code'=>0,'msg'=>'图片上传失败:'.$return['msg']),'上传图片');
                    }else{
                        $image[]=array('gi_img'=>$return['url'],'gi_sort'=>0,'gi_status'=>1,'gi_create_time'=>time(),'gi_add_user_id'=>session('uid'),'gi_add_user_name'=>session('user.real_name'));
                    }
                }
            }
            db()->startTrans();
            $res=db('goods')->insertGetId($data);
            //添加权限
            if($res>0){

            }else{
                return return_json(array('code'=>0,'msg'=>'商品添加失败'),'添加商品');
            }
            foreach($norm as $k=>$v){
                $norm[$k]['g_id']=$res;
            }
            foreach($image as $k=>$v){
                $image[$k]['g_id']=$res;
            }
            $res1=db('goods_norm')->insertAll($norm);
            $res2=db('goods_img')->insertAll($image);
            if($res1 && $res2){
                db()->commit();
                db('goods_log')->insert(array('admin_user_id'=>session('uid'),'admin_user_name'=>session('user.real_name'),'g_id'=>$res,'create_time'=>time(),'action'=>'新增商品,商品id:'.$res));
                $norm_ids=db('goods_norm')->field('gn_id')->where(array('g_id'=>$res))->select();
                $ids=':';
                foreach($norm_ids as $v){
                    $ids.=$v['gn_id'].',';
                }
                $ids=substr($ids,0,-1);
                db('goods_log')->insert(array('admin_user_id'=>session('uid'),'admin_user_name'=>session('user.real_name'),'g_id'=>$res,'create_time'=>time(),'action'=>'新增规格,规格id:'.$ids));
                return return_json(array('code'=>1,'msg'=>'商品添加成功'),'添加商品');
            }else{
                db()->rollback();
                return return_json(array('code'=>0,'msg'=>'商品添加失败'),'添加商品');
            }
		}
    }
    //删除规格
    function norm_del(){
        if(Request()->isAjax()){
            $id=Request()->post('id');
            $norm=db('goods_norm')->where(array('gn_id'=>$id))->find();
            db()->startTrans();
            $res=db('goods_norm')
                ->where(array('gn_id'=>$id))
                ->update(array('gn_status'=>3,'gn_update_time'=>time()));
            db('goods_log')->insert(array('admin_user_id'=>session('uid'),'admin_user_name'=>session('user.real_name'),'g_id'=>$norm['g_id'],'create_time'=>time(),'action'=>'删除规格,规格id:'.$id));
            $other_norm=db('goods_norm')->where(array('g_id'=>$norm['g_id'],'gn_status'=>array('in','1,2')))->count();
            if($other_norm>0){
                $res1=1;
            }else{
                $res1=db('goods')->where(array('g_id'=>$norm['g_id']))->update(array('g_status'=>3,'g_update_time'=>time()));
                db('goods_log')->insert(array('admin_user_id'=>session('uid'),'admin_user_name'=>session('user.real_name'),'g_id'=>$norm['g_id'],'create_time'=>time(),'action'=>'删除商品,商品id：'.$norm['g_id'].',规格id:'.$id));
            }
            if($res!=false && $res1!=false){
                db()->commit();
                return return_json(array('code'=>1,'msg'=>'删除成功！'),'删除规格');die;
            }else{
                db()->rollback();
                return return_json(array('code'=>0,'msg'=>$res.'删除失败！'.$res1),'删除规格');die;
            }
        }
    }
    //修改商品
    public function regoods(){
        if(request()->isGet()){
            //get，加载页面
            $id=request()->get('id');
            $goods=db('goods')
                ->where(array('g_id'=>$id))
                ->find();
            $norm=db('goods_norm')
                ->where(array('g_id'=>$id,'gn_status'=>array('in','1,2')))
                ->select();
            $img=db('goods_img')
                ->where(array('g_id'=>$id,'gi_status'=>array('in','1,2')))
                ->select();
            $goods_label=explode(',','0'.$goods['gl_ids'].'0');
            $type=db('goods_type')
                ->where(array('gt_status'=>1))
                ->order("gt_sort desc,gt_type")
                ->select();
            //分类
            $type1=array();
            $type2=array();
            foreach($type as $k=>$v){
                if($v['gt_type']==1){
                    $type1[]=$v;
                }
                if($v['gt_type']==2){
                    $type2[]=$v;
                }
                if($v['gt_type']==3){
                    $type3[]=$v;
                }
            }
            $label=db('goods_label a')
                ->where(array('a.gl_status'=>1,'gl_id'=>array('neq',2)))
                ->order("a.gl_sort")
                ->select();
            //标签
            $brand=db('goods_brand a')
                ->where(array('a.gb_status'=>1))
                ->order("a.gb_sort")
                ->select();
            //品牌
            $this->assign('goods',$goods);
            $this->assign('goods_label',$goods_label);
            $this->assign('type1',$type1);
            $this->assign('type2',$type2);
            $this->assign('type3',$type3);
            $this->assign('label',$label);
            $this->assign('brand',$brand);
            $this->assign('norm',$norm);
            $this->assign('img',$img);
            return $this->view->fetch();
        }else if(request()->isAjax()) {
            $data1 = request()->post();
            $id=$data1['id'];
            $data['g_name'] = $data1['g_name'];
            $data['gt_id'] = $data1['gt_id'];
            $data['gb_id'] = $data1['gb_id'];
            $data['g_sort'] = $data1['g_sort'];
            $data['g_status'] = $data1['g_status'];
            $data['g_is_index_recommen'] = $data1['g_is_index_recommen'];
            if(!isset($data1['label'])){
                $data1['label']='';
            }
            $data['label'] = $data1['label'];
            if (!isset($data1['editorValue'])) {
                $data1['editorValue'] = '';
            }
            $data['editorValue'] = $data1['editorValue'];
            if ($data['g_name'] == '') {
                return return_json(array('code' => 0, 'msg' => '请输入商品名称'), '修改商品');
            }
            $system = db('system')->find();
            $gt_id = $data['gt_id'];
            $data['g_content'] = $data['editorValue'];
            unset($data['editorValue']);
            $goods_type = db('goods_type a')
                ->field("a.*,b.gt_id as gt_id2,c.gt_id as gt_id1")
                ->join("fr_goods_type b", "a.gt_pid = b.gt_id", "left")
                ->join("fr_goods_type c", "b.gt_pid = c.gt_id", "left")
                ->where(array('a.gt_status' => 1, 'a.gt_id' => $gt_id))
                ->find();
            if (empty($goods_type)) {
                return return_json(array('code' => 0, 'msg' => '请选择可使用的分类'), '修改商品');
            }
            $data['gt_id1'] = $goods_type['gt_id1'];
            $data['gt_id2'] = $goods_type['gt_id2'];
            $label = $data['label'];
            if (!empty($label)) {
                $label_str = ',' . implode(',', $label) . ',';
            } else {
                $label_str = '';
            }
            $data['gl_ids'] = $label_str;
            $data['g_create_time'] = time();
            $data['g_add_user_id'] = session('uid');
            $data['g_add_user_name'] = session('user.real_name');
            unset($data['label']);
            //以上为商品属性判断
            $gn_ids = $data1['gn_ids'];//规格id
            $gi_ids = $data1['gi_ids'];//图片id
            $old_price = $data1['old_price'];//原价
            $gn_name = $data1['gn_name'];
            $gn_price = $data1['gn_price'];
            $gn_stock = $data1['gn_stock'];
            $gn_old_price = $data1['gn_old_price'];
            $gn_weight = $data1['gn_weight'];
            $gn_details_number = $data1['gn_details_number'];
            $gn_details_unit = $data1['gn_details_unit'];
            $gn_sort = $data1['gn_sort'];
            $norm = array();
            $old_norm = array();
            foreach ($gn_name as $k => $v) {
                if($gn_ids[$k]==0){
                    if ($v != '' && $gn_price[$k] > 0 && $gn_weight[$k] > 0) {
                        if ($gn_old_price[$k] > 0 && $gn_old_price[$k] < $gn_price[$k]) {
                            return return_json(array('code' => 0, 'msg' => '所有的原价都必须大于出售价格或为0'), '修改商品');
                        }
                        if ($gn_old_price[$k] <= 0) {
                            $gn_old_price[$k] = 0;
                        }
                        if ($gn_stock[$k] <= 0) {
                            $gn_stock[$k] = 0;
                        }
                        if ($gn_details_number[$k] <= 1) {
                            $gn_details_number[$k] = 1;
                        }
                        if ($gn_details_unit[$k] <= 1) {
                            $gn_details_unit[$k] = '件';
                        }
                        if ($gn_sort[$k] <= 0) {
                            $gn_sort[$k] = 0;
                        }
                        $norm[$k] = array('gn_price' => $gn_price[$k], 'gn_old_price' => $gn_old_price[$k], 'gn_stock' => $gn_stock[$k], 'gn_name' => $v, 'gn_weight' => $gn_weight[$k], 'gn_one_number' => '', 'gn_status' => 1, 'gn_create_time' => time(), 'gn_sort' => $gn_sort[$k], 'gn_add_user_id' => session('uid'), 'gn_add_user_name' => session('user.real_name'), 'gn_details_number' => $gn_details_number[$k], 'gn_details_unit' => $gn_details_unit[$k]);
                    }
                }else{
                    if ($v != '' && $gn_price[$k] > 0 && $gn_weight[$k] > 0) {
                        if ($gn_old_price[$k] > 0 && $gn_old_price[$k] < $gn_price[$k]) {
                            return return_json(array('code' => 0, 'msg' => '所有的原价都必须大于出售价格或为0'), '修改商品');
                        }
                        if ($gn_old_price[$k] <= 0) {
                            $gn_old_price[$k] = 0;
                        }
                        if ($gn_stock[$k] <= 0) {
                            $gn_stock[$k] = 0;
                        }
                        if ($gn_details_number[$k] <= 1) {
                            $gn_details_number[$k] = 1;
                        }
                        if ($gn_details_unit[$k] <= 1) {
                            $gn_details_unit[$k] = '件';
                        }
                        if ($gn_sort[$k] <= 0) {
                            $gn_sort[$k] = 0;
                        }
                        $old_norm[$k] = array('gn_id'=>$gn_ids[$k],'gn_price' => $gn_price[$k], 'gn_old_price' => $gn_old_price[$k], 'gn_stock' => $gn_stock[$k], 'gn_name' => $v, 'gn_weight' => $gn_weight[$k], 'gn_details_number' => $gn_details_number[$k], 'gn_details_unit' => $gn_details_unit[$k],'old_price'=>$old_price[$k]);
                    }else{
                        if($v==''){
                            return return_json(array('code' => 0, 'msg' => '请输入对应的规格名称'), '修改商品');
                        }
                        if($gn_price[$k]<=0){
                            return return_json(array('code' => 0, 'msg' => '请输入对应的售价'), '修改商品');
                        }
                        if($gn_weight[$k]<=0){
                            return return_json(array('code' => 0, 'msg' => '请输入对应的重量'), '修改商品');
                        }
                    }
                }
            }
            if ((empty($norm) || count($norm) < 1) && (empty($old_norm) || count($old_norm) < 1)) {
                return return_json(array('code' => 0, 'msg' => '至少有一个商品规格'), '修改商品');
            }
            $upload = new Upload();
            $file = Request()->file("g_img");
            if (!$file) {
//                $data['g_img'] = $system['goods_img'];
                unset($data['g_img']);
            } else {
                $return = $upload->upload($file);
                if ($return['code'] != 1) {
                    return return_json(array('code' => 0, 'msg' => '图片上传失败:' . $return['msg']), '上传图片');
                } else {
                    $data['g_img'] = $return['url'];
                }
            }
            $old_img=array();
            if(count($gi_ids)>0){
                foreach($gi_ids as $v){
                    if($v>0){
                        $file=Request()->file("gi_img_".$v);
                        if($file){
                            $return = $upload->upload($file);
                            if ($return['code'] != 1) {
                                return return_json(array('code' => 0, 'msg' => '图片上传失败:' . $return['msg']), '上传图片');
                            } else {
                                $old_img[] = array('gi_img' => $return['url'],'gi_id'=>$v,'gi_update_time'=>time());
                            }
                        }
                    }
                }
            }
            $file = Request()->file("gi_img");
            if (!$file) {
//                $image = array(array('gi_img' => $system['goods_image'], 'gi_sort' => 0, 'gi_status' => 1, 'gi_create_time' => time(), 'gi_add_user_id' => session('uid'), 'gi_add_user_name' => session('user.real_name')));
                $image=array();
            } else {
                foreach ($file as $v) {
                    $return = $upload->upload($v);
                    if ($return['code'] != 1) {
                        return return_json(array('code' => 0, 'msg' => '图片上传失败:' . $return['msg']), '上传图片');
                    } else {
                        $image[] = array('gi_img' => $return['url'], 'gi_sort' => 0, 'gi_status' => 1, 'gi_create_time' => time(), 'gi_add_user_id' => session('uid'), 'gi_add_user_name' => session('user.real_name'));
                    }
                }
            }

            db()->startTrans();
            $res = db('goods')->where(array('g_id'=>$id))->update($data);
            //添加权限
            if ($res > 0) {

            } else {
                return return_json(array('code' => 0, 'msg' => '商品修改失败'), '修改商品');
            }
            $time=time();
            foreach ($norm as $k => $v) {
                $norm[$k]['g_id'] = $id;
                $norm[$k]['gn_create_time'] = $time;
            }
            foreach ($image as $k => $v) {
                $image[$k]['g_id'] = $id;
            }
            if(!empty($norm) && count($norm)>0){
                $res1 = db('goods_norm')->insertAll($norm);
            }else{
                $res1=1;
            }
            if(!empty($image) && count($image)>0){
                $res2 = db('goods_img')->insertAll($image);
            }else{
                $res2 = 1;
            }
            if(!empty($old_img) && count($old_img)>0){
                foreach($old_img as $v){
                    $gi_id=$v['gi_id'];
                    unset($v['gi_id']);
                    db('goods_img')->where(array('gi_id'=>$gi_id))->update($v);
                }
            }
            if(!empty($old_norm) && count($old_norm)>0){
                foreach($old_norm as $v){
                    $norm_id=$v['gn_id'];
                    if($v['old_price']!=$v['gn_price']){
                        db('goods_log')->insert(array('admin_user_id' => session('uid'), 'admin_user_name' => session('user.real_name'), 'g_id' => $id, 'create_time' => time(), 'action' => '修改规格，id='.$norm_id.',名称='.$v['gn_name'].'，原价格='.$v['old_price'].'，现价格='.$v['gn_price']));
                    }
                    unset($v['gn_id'],$v['old_price']);
                    $v['gn_update_time']=time();
                    db('goods_norm')->where(array('gn_id'=>$norm_id))->update($v);
                }
            }
            if ($res1 && $res2) {
                db()->commit();
//                db('goods_log')->insert(array('admin_user_id' => session('uid'), 'admin_user_name' => session('user.real_name'), 'g_id' => $res, 'create_time' => time(), 'action' => '新增商品,商品id:' . $res));
                $norm_ids = db('goods_norm')->field('gn_id')->where(array('g_id' => $id,'gn_create_time'=>$time))->select();
                if(!empty($norm_ids)){
                    $ids = ':';
                    foreach ($norm_ids as $v) {
                        $ids .= $v['gn_id'] . ',';
                    }
                    $ids = substr($ids, 0, -1);
                    db('goods_log')->insert(array('admin_user_id' => session('uid'), 'admin_user_name' => session('user.real_name'), 'g_id' => $id, 'create_time' => time(), 'action' => '新增规格,规格id:' . $ids));
                }
                return return_json(array('code' => 1, 'msg' => '商品修改成功'), '修改商品');
            } else {
                db()->rollback();
                return return_json(array('code' => 0, 'msg' => '商品修改失败'), '修改商品');
            }
        }
    }
    //禁用商品
    function goods_del(){
        if(request()->isAjax()){
            $id=request()->post('id');
            $res=db('goods')
                ->where(array('g_id'=>$id))
                ->update(array('g_status'=>2,'g_update_time'=>time()));
            if($res!==false){
                return return_json(array('code'=>1,'msg'=>'禁用成功'),'禁用商品');
            }else{
                return return_json(array('code'=>0,'msg'=>'禁用失败'),'禁用商品');
            }
        }
    }
    //启用商品
    function goods_use(){
        if(request()->isAjax()){
            $id=request()->post('id');
            $res=db('goods')
                ->where(array('g_id'=>$id))
                ->update(array('g_status'=>1,'g_update_time'=>time()));
            if($res!==false){
                return return_json(array('code'=>1,'msg'=>'启用成功'),'启用商品');
            }else{
                return return_json(array('code'=>0,'msg'=>'启用失败'),'启用商品');
            }
        }
    }
    //商品详情
    function goods_details(){
        if(request()->isGet()){
            //get，加载页面
            $id=request()->get('id');
            $goods=db('goods')
                ->where(array('g_id'=>$id))
                ->find();
            $norm=db('goods_norm')
                ->where(array('g_id'=>$id,'gn_status'=>array('in','1,2')))
                ->select();
            $img=db('goods_img')
                ->where(array('g_id'=>$id,'gi_status'=>array('in','1,2')))
                ->select();
            $goods_label=explode(',','0'.$goods['gl_ids'].'0');
            $type=db('goods_type')
                ->where(array('gt_status'=>1,'gt_id'=>$goods['gt_id']))
                ->order("gt_sort desc,gt_type")
                ->select();
            //分类
            $type3=array();
            foreach($type as $k=>$v){
                if($v['gt_type']==3){
                    $type3[]=$v;
                }
            }
            $label=db('goods_label a')
                ->where(array('a.gl_status'=>1,'gl_id'=>array('in',$goods['gl_ids'])))
                ->order("a.gl_sort")
                ->select();
            //标签
            $brand=db('goods_brand a')
                ->where(array('a.gb_status'=>1,'gb_id'=>$goods['gb_id']))
                ->order("a.gb_sort")
                ->select();
            //品牌
            $log=db('goods_log')
                ->where(array('g_id'=>$id))
                ->order("id desc")
                ->select();
            $this->assign('goods',$goods);
            $this->assign('goods_label',$goods_label);
            $this->assign('type3',$type3);
            $this->assign('label',$label);
            $this->assign('brand',$brand);
            $this->assign('norm',$norm);
            $this->assign('img',$img);
            $this->assign('log',$log);
            return $this->view->fetch();
        }
    }
    //需求商品列表
    function need_list(){
        $where=array('a.gd_id'=>array('gt',0));
        $name=Request()->param('name');
        //名称
        $mobile=Request()->param('mobile');
        //申请人电话
        $status=Request()->param('status');
        //状态
        $start_time=strtotime(Request()->param('start_time'));
        $end_time=strtotime(Request()->param('end_time'));
        $page=Request()->param('page');
        $size=Request()->param('size');
        if($page<1){
            $page=1;
        }
        if($size<15){
            $size=15;
        }
        $now=($page-1)*$size;
        if($name!=''){
            $where['a.gd_name']=array('like','%'.$name.'%');
        }
        if($status>0){
            if($status==1){
                $where['a.gd_status']=1;
            }else{
                $where['a.gd_status']=2;
            }

        }
        $where_time=array(array('gt',0),array('gt',0));
        if($start_time>0){
            $where_time[]=array('egt',$start_time);
        }else{
            $start_time='';
        }
        if($end_time>0){
            $where_time[]=array('elt',$end_time);
        }else{
            $end_time='';
        }
        $where['a.gd_create_time']=$where_time;
        $goods=db('goods_demand a')
            ->field("a.*,b.u_mobile,b.u_real_name,c.gt_name")
            ->join('fr_user b','a.u_id = b.u_id','left')
            ->join('fr_goods_type c','a.gt_id = c.gt_id','left')
            ->order('a.gd_id desc')
            ->where($where)
            ->limit("$now,$size")
            ->select();
        //标签列表
        $count=db('goods_demand a')
            ->join('fr_user b','a.u_id = b.u_id','left')
            ->where($where)
            ->count();
        //等级信息
        $page_str=page($page,$size,$count,count($goods));//分页
        $this->view->assign('page_str',$page_str);
        $this->view->assign('data',$goods);
        $this->assign('status',$status);
        $this->assign('name',$name);
        $this->assign('mobile',$mobile);
        $this->assign('start_time',$start_time);
        $this->assign('end_time',$end_time);
        $this->assign('page',$page);
        $this->assign('size',$size);
        $this->assign('count',$count);
        return $this->view->fetch();
    }
    //需求详情
    function need_details(){
        if(request()->isGet()) {
            $id = request()->get('id');
            $goods = db('goods_demand a')
                ->field("a.*,b.u_mobile,b.u_real_name,c.gt_name")
                ->join('fr_user b', 'a.u_id = b.u_id', 'left')
                ->join('fr_goods_type c', 'a.gt_id = c.gt_id', 'left')
                ->where(array('a.gd_id' => $id))
                ->find();
            $img = explode(',', $goods['gd_img']);
            $this->assign('img', $img);
            $this->assign('goods', $goods);
            return $this->view->fetch();
        }
    }
    //需求处理
    function need_handle(){
        if(request()->isGet()) {
            $id = request()->get('id');
            $goods = db('goods_demand a')
                ->field("a.*,b.u_mobile,b.u_real_name,c.gt_name")
                ->join('fr_user b', 'a.u_id = b.u_id', 'left')
                ->join('fr_goods_type c', 'a.gt_id = c.gt_id', 'left')
                ->where(array('a.gd_id' => $id))
                ->find();
            $img = explode(',', $goods['gd_img']);
            $this->assign('img', $img);
            $this->assign('goods', $goods);
            return $this->view->fetch();
        }else if(request()->isAjax()){
            $data=request()->post();
            $id=$data['id'];
            $g_id=$data['g_id'];
            if($g_id<=0 || !is_numeric($g_id)){
                $g_id=0;
            }
            $res=db('goods_demand a')
                ->where(array('a.gd_id' => $id))
                ->update(array('gd_status'=>2,'gd_back_goods_id'=>$g_id,'gd_admin_user_id'=>session('uid'),'gd_admin_user_name'=>session('user.real_name'),'gd_update_time'=>time()));
            if($res!==false){
                return return_json(array('code'=>1,'msg'=>'处理成功'),'需求处理');
            }else{
                return return_json(array('code'=>0,'msg'=>'处理失败'),'需求处理');
            }
        }
    }
    //导出商品
    public function out_goods()
    {
//        $file_name="" ;
//        $header = array(
//            '0' => '参数ID',
//            '1' => '参数名称',
//            '2' => '统计次数',
//            '3' => '统计次数百分比',
//            '4' => '唯一用户数',
//            '5' => '唯一用户数百分比',
//            '6' => '人均次数'
//        );
//        $csvList = array(array("111", "title", "12", "100%", "23", "50%", "4")) ;
//        export_csv($csvList, $header, $file_name) ;
//        die;
        $where=array('a.g_id'=>array('gt',0));
        $where['f.gn_status']=array('in','1,2');
        $where['a.g_status']=array('in','1,2');
        $name=Request()->param('name');
        //名称
        $status=Request()->param('status');
        //状态
        $start_time=strtotime(Request()->param('start_time'));
        $end_time=strtotime(Request()->param('end_time'));
        if($name!=''){
            $where['a.g_name']=array('like','%'.$name.'%');
        }
        if($status>0){
            if($status==1){
                $where['f.gn_status']=1;
            }else{
                $where['f.gn_status']=2;
            }

        }
        $where_time=array(array('gt',0),array('gt',0));
        if($start_time>0){
            $where_time[]=array('egt',$start_time);
        }else{
            $start_time='';
        }
        if($end_time>0){
            $where_time[]=array('elt',$end_time);
        }else{
            $end_time='';
        }
        $where['f.gn_create_time']=$where_time;
        $goods=db('goods a')
            ->field("a.g_id,a.g_name,a.g_status,a.g_is_index_recommen,a.gl_ids,a.g_sales,b.gt_name,c.gb_name,d.gt_name as gt_name1,e.gt_name as gt_name2,f.*")
            ->join('fr_goods_type b','a.gt_id = b.gt_id','left')
            ->join('fr_goods_type d','d.gt_id = b.gt_pid','left')
            ->join('fr_goods_type e','e.gt_id = d.gt_pid','left')
            ->join('fr_goods_brand c','a.gb_id = c.gb_id','left')
            ->join('fr_goods_norm f','a.g_id=f.g_id','left')
            ->order('a.g_sort desc,a.g_status,f.gn_sort desc,f.gn_status')
            ->where($where)
            ->select();
        //标签列表
        foreach($goods as $k=>$v){
            $goods[$k]['gn_details_price']=round($v['gn_price']/$v['gn_details_number'],2).'/'.$v['gn_details_unit'];
            if (preg_match('/,1,/', $v['gl_ids'])) {
                //匹配成功
                $goods[$k]['special']=1;
            } else {
                //匹配失败
                $goods[$k]['special']=0;
            }
        }
        $header = array(
            '0' => '商品ID',
            '1' => '分类',
            '2' => '品牌',
            '3' => '商品名称',
            '4' => '规格ID',
            '5' => '规格',
            '6' => '价格',
            '7' => '详细价格',
            '8' => '销量',
            '9' => '商品状态',
            '10' => '规格状态',
            '11' => '是否特价',
            '12' => '是否首页推荐',
        );
        $data=array();
        foreach($goods as $v){
            $data1=array();
            $data1=array($v['g_id'],$v['gt_name2'].'--'.$v['gt_name1'].'--'.$v['gt_name'],$v['gb_name'],$v['g_name'],$v['gn_id'],$v['gn_name'],$v['gn_price'],$v['gn_details_price'],$v['g_sales']);
            if($v['g_status'] == 1){
                $data1[]='已上架';
            }else{
                $data1[]='已下架';
            }
            if($v['gn_status'] == 1){
                $data1[]='启用';
            }else{
                $data1[]='冻结';
            }
            if($v['special'] == 1){
                $data1[]='特价';
            }else{
                $data1[]='非特价';
            }
            if($v['g_is_index_recommen'] == 1){
                $data1[]='首页推荐';
            }else{
                $data1[]='不推荐';
            }
            $data[]=$data1;
        }
        $file_name='goods_'.date('Y_m_d_H_i_s');
        export_csv($data, $header, $file_name) ;
        die;
    }
    //添加商品
    public function add_goods_csv(){
        if(request()->isGet()){
            return $this->view->fetch();
        }else if(request()->isAjax()){
            set_time_limit(0);
            $file=request()->file('csv_file');
            if(!$file){
                return return_json(array('code'=>0,'msg'=>'请选择文件'),'导入商品');
            }
            //以下将模板传入第三方
//            $upload = new Upload();
//            $return=$upload->upload($file);
//            if($return['code']!=1){
//                return return_json(array('code'=>0,'msg'=>'图片上传失败:'.$return['msg']),'上传模板');
//            }else{
//                $data['g_img']=$return['url'];
//            }
//            echo $data['g_img'];die;
            //http://sczxyx-mall.oss-cn-chengdu.aliyuncs.com/a5e6c20190821113542811737.csv
            //模板地址
            //以上将模板传入第三方
            $ext   = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            if($ext!='csv' && $ext!='CSV'){
                return return_json(array('code'=>0,'msg'=>'只支持csv文件'),'导入商品');
            }
            $csv_file = fopen($file->getInfo('tmp_name'), 'r');
            //打开文件
            while($data=fgetcsv($csv_file,1000,",")){
                $data = eval('return '.iconv('gbk','utf-8',var_export($data,true)).';');//防止乱码
                //读取有保单号的数据
                $list[] = $data;

            }
            //将文件内容读取未数组
            unset($list[0]);//去除第一行
            $system=db('system')->find();
            //系统设置
            $image=array(array('gi_img'=>$system['goods_image'],'gi_sort'=>0,'gi_status'=>1,'gi_create_time'=>time(),'gi_add_user_id'=>session('uid'),'gi_add_user_name'=>session('user.real_name')));
            //默认轮播图片
            $all_goods=array();
            $all_goods_type=array();
            $all_brand=array();
            $time=time();
            foreach($list as $v){
                $name=$v[2];
                //商品名称
                foreach($all_goods as $vv){
                    if($name==$vv['g_name']){
                        $goods=$vv;
                    }
                }
                if(empty($goods)){
                    //没有该商品
                    $goods=db('goods')->field("g_id,g_name")->where(array('g_name'=>$name,'g_status'=>array('in','1,2')))->find();
                    if(!empty($goods)){
                        $all_goods[]=$goods;
                    }else{
                        $type=explode('--',$v[0]);
                        //分类
                        foreach($all_goods_type as $vv){
                            if($type[2]==$vv['gt_name']){
                                $goods_type=$vv;
                            }
                        }
                        if(empty($goods_type)){
                            $goods_type=db('goods_type a')
                                ->field("a.*,c.gt_id as gt_id1,b.gt_id as gt_id2")
                                ->join("fr_goods_type b","a.gt_pid = b.gt_id","left")
                                ->join("fr_goods_type c","b.gt_pid = c.gt_id","left")
                                ->where(array('a.gt_name'=>$type[2],'a.gt_status'=>1))
                                ->find();
                            if(!empty($goods_type)){
                                $all_goods_type[]=$goods_type;
                            }else{
                                $goods_type=array('gt_id'=>0,'gt_id1'=>0,'gt_id2'=>0);
                            }
                        }
                        //分类处理
                        $brand=$v[1];
                        //品牌
                        foreach($all_brand as $vv){
                            if($type[2]==$vv['gb_name']){
                                $goods_brand=$vv;
                            }
                        }
                        if(empty($goods_brand)) {
                            $goods_brand = db('goods_brand')
                                ->where(array('gb_name' => $brand, 'gb_status' => 1))
                                ->find();
                            if(!empty($goods_brand)){
                                $all_brand[]=$goods_brand;
                            }else{
                                $goods_brand=array('gb_id'=>0);
                            }
                        }
                        //品牌处理
                        $sort=$v[13] > 0 ? $v[13]:0;
                        //排序
                        $status=$v[9]=='已上架' ? 1:2;
                        //商品状态
                        $index_recommen=$v[12] == '首页推荐' ? 1:2;
                        //首页推荐
                        if($v[11]=='特价'){
                            $label=',1,';
                        }else{
                            $label='';
                        }
                        $data['g_name']=$v[2];
                        $data['gt_id']=$goods_type['gt_id'];
                        $data['gt_id1']=$goods_type['gt_id1'];
                        $data['gt_id2']=$goods_type['gt_id2'];
                        $data['gb_id']=$goods_brand['gb_id'];
                        $data['g_sort']=$sort;
                        $data['g_status']=$status;
                        $data['g_is_index_recommen']=$index_recommen;
                        $data['gl_ids']=$label;
                        $data['g_content']='';
                        $data['g_create_time']=time();
                        $data['g_add_user_id']=session('uid');
                        $data['g_add_user_name']=session('user.real_name');
                        $data['g_img']=$system['goods_img'];
                        $res=db('goods')->insertGetId($data);
                        db('goods_log')->insert(array('admin_user_id'=>session('uid'),'admin_user_name'=>session('user.real_name'),'g_id'=>$res,'create_time'=>time(),'action'=>'新增商品,商品id:'.$res));
                        $image[0]['g_id']=$res;
                        $res2=db('goods_img')->insertAll($image);
                        unset($image['g_id']);
                        $goods=array('g_id'=>$res,'g_name'=>$data['g_name']);
                        $all_goods[]=$goods;
                        unset($goods_type,$goods_brand);
                    }
                }
                $norm[]=array(
                    'g_id'=>$goods['g_id'],
                    //商品id
                    'gn_price'=>$v[4],
                    //价格
                    'gn_old_price'=>0,
                    //原价
                    'gn_stock'=>$v[6],
                    //库存
                    'gn_name'=>$v[3],
                    //规格
                    'gn_weight'=>$v[5],
                    //重量（kg）
                    'gn_details_number'=>$v[7]>1?$v[7]:1,
                    //详细价格数量
                    'gn_details_unit'=>$v[8]!=''?$v[8]:'件',
                    //详细价格单位
                    'gn_status'=>$v[10]=='启用'? 1:2,
                    //规格状态
                    'gn_one_number'=>'',
                    'gn_create_time'=>$time,
                    'gn_sort'=>0,
                    'gn_add_user_id'=>session('uid'),
                    'gn_add_user_name'=>session('user.real_name')
                );
                unset($goods);
            }
            db('goods_norm')->insertAll($norm);
            $norm_ids=db('goods_norm')->field('g_id,gn_id')->where(array('gn_create_time'=>$time))->select();
            $t_ids=array();
            foreach($norm_ids as $v){
                if(!isset($t_ids[$v['g_id']]['ids'])){
                    $t_ids[$v['g_id']]['ids']='';
                }
                $t_ids[$v['g_id']]['g_id']=$v['g_id'];
                $t_ids[$v['g_id']]['ids'].=$v['gn_id'].',';
            }
            foreach($t_ids as $v){
                $ids=substr($v['ids'],0,-1);
                db('goods_log')->insert(array('admin_user_id'=>session('uid'),'admin_user_name'=>session('user.real_name'),'g_id'=>$v['g_id'],'create_time'=>time(),'action'=>'新增规格,规格id:'.$ids));
            }
            return return_json(array('code'=>1,'msg'=>'导入成功'),'导入商品');

        }
    }
}
